import DataBus from '../databus';
import Enemy from '../npc/enemy';
import Player from '../player/index';
import Ally from '../ally/index';
import { SCREEN_WIDTH, SCREEN_HEIGHT } from '../render';
import RenderManager from './render-manager';

const ENEMY_TYPES = {
  NORMAL: 1,
  ELITE: 2
};

const WAVE_CONFIG = [
  { enemyCount: 2, eliteCount: 0 }, // Wave 1
  { enemyCount: 3, eliteCount: 1 }, // Wave 2
  { enemyCount: 3, eliteCount: 2 }, // Wave 3
  { enemyCount: 4, eliteCount: 2 }, // Wave 4
  { enemyCount: 4, eliteCount: 3 }, // Wave 5
];

export default class CharacterManager {
  constructor(canvas) {
    this.canvas = canvas;  // 保存canvas引用
    this.databus = new DataBus();
    this.allies = [];     // 队友数组
    
    // 初始化渲染管理器
    this.renderManager = new RenderManager(this.databus);
    
    // 初始化属性
    this.currentWave = 0;
    this.waveCleared = true;
    this.waveDelay = 180; // 3秒 (60帧/秒)
    this.waveTimer = 0;
    this.onGameOver = null; // 游戏结束回调函数
    
    // 初始化游戏
    this.initGame();
  }

  // 统一初始化方法
  initGame() {
    this.initPlayer();
    this.initAllies(3);
    this.initEnemys();
  }

  // 初始化玩家
  initPlayer() {
    this.databus.player = new Player(this.canvas);
    console.log('Player initialized');
  }

  // 在CharacterManager类中添加这个方法
initAllies(count = 3) {
  // 确保玩家已初始化
  //if (!this.databus.player) {
  //  console.error('Error: Player must be initialized before allies');
   // return;
  //}

  // 清除现有队友
  this.allies = [];
  this.databus.allies = [];

  // 生成新队友
  for (let i = 0; i < count; i++) {
    try {
      const ally = new Ally(Math.random() > 0.5 ? 1 : 2); // 随机类型
      
      // 设置初始位置（围绕玩家呈圆形分布）
      const angle = (i / count) * Math.PI * 2;
      const radius = 120;
      ally.x = this.databus.player.x + Math.cos(angle) * radius;
      ally.y = this.databus.player.y + Math.sin(angle) * radius;
      
      // 确保不会超出屏幕边界
      ally.x = Math.max(30, Math.min(SCREEN_WIDTH - 30, ally.x));
      ally.y = Math.max(30, Math.min(SCREEN_HEIGHT - 30, ally.y));
      
      ally.visible = true;
      
      // 添加到管理列表
      this.allies.push(ally);
      this.databus.allies.push(ally);
      
      console.log(`Ally ${i} initialized at (${ally.x.toFixed(0)},${ally.y.toFixed(0)})`);
      
    } catch (e) {
      console.error('Failed to create ally:', e);
    }
  }
}

// 敌人初始化方法
initEnemys() {
  // 清除现有敌人
  this.databus.enemies = [];
  
  // 重置波次状态
  this.currentWave = 0;
  this.waveCleared = true;
  this.waveTimer = this.waveDelay;
  
  console.log('Enemy system initialized, ready for first wave');
}

// 配套的敌人生成方法（需保留原有spawnEnemy）
/*spawnEnemy(type = ENEMY_TYPES.NORMAL) {
  const enemy = this.databus.pool.getItemByClass('enemy', Enemy);
  
  // 从屏幕边缘随机生成
  const side = Math.floor(Math.random() * 4); // 0:上,1:右,2:下,3:左
  let x, y;
  
  switch(side) {
    case 0: // 上边
      x = Math.random() * SCREEN_WIDTH;
      y = -50;
      break;
    case 1: // 右边
      x = SCREEN_WIDTH + 50;
      y = Math.random() * SCREEN_HEIGHT;
      break;
    case 2: // 下边
      x = Math.random() * SCREEN_WIDTH;
      y = SCREEN_HEIGHT + 50;
      break;
    case 3: // 左边
      x = -50;
      y = Math.random() * SCREEN_HEIGHT;
      break;
  }

  enemy.init(type, x, y);
  this.databus.enemies.push(enemy);
  
  console.log(`Spawned ${type === ENEMY_TYPES.ELITE ? 'elite' : 'normal'} enemy at ${x},${y}`);
}*/

  // 生成敌人
  spawnEnemy(type = ENEMY_TYPES.NORMAL) {
    const enemy = this.databus.pool.getItemByClass('enemy', Enemy);
    
    // 随机生成敌人位置（在屏幕边缘）
    const side = Math.floor(Math.random() * 4); // 0:上, 1:右, 2:下, 3:左
    let x, y;
    
    switch(side) {
      case 0: // 上
        x = Math.random() * SCREEN_WIDTH;
        y = -50;
        break;
      case 1: // 右
        x = SCREEN_WIDTH + 50;
        y = Math.random() * SCREEN_HEIGHT;
        break;
      case 2: // 下
        x = Math.random() * SCREEN_WIDTH;
        y = SCREEN_HEIGHT + 50;
        break;
      case 3: // 左
        x = -50;
        y = Math.random() * SCREEN_HEIGHT;
        break;
    }

    enemy.init(type, x, y);
    this.databus.enemies.push(enemy);
    
    console.log(`Spawned ${type === ENEMY_TYPES.ELITE ? 'elite' : 'normal'} enemy at:`, x, y);
  }

  // 开始新的一波
  startNewWave() {
    // 计算当前波次配置（循环使用预设波次）
    const waveIndex = this.currentWave % WAVE_CONFIG.length;
    const waveConfig = WAVE_CONFIG[waveIndex];
    
    // 随着波次增加，敌人数量逐渐增加
    const waveMultiplier = 1 + Math.floor(this.currentWave / WAVE_CONFIG.length) * 0.2;
    const enemyCount = Math.floor(waveConfig.enemyCount * waveMultiplier);
    const eliteCount = Math.floor(waveConfig.eliteCount * waveMultiplier);
    
    // 生成普通敌人
    for (let i = 0; i < enemyCount; i++) {
      this.spawnEnemy(ENEMY_TYPES.NORMAL);
    }
    
    // 生成精英敌人
    for (let i = 0; i < eliteCount; i++) {
      this.spawnEnemy(ENEMY_TYPES.ELITE);
    }

    this.waveCleared = false;
    this.currentWave++;
    
    console.log(`Started wave ${this.currentWave} (${enemyCount} normal, ${eliteCount} elite)`);
  }

  // 检查当前波次是否结束
  checkWaveStatus() {
    if (!this.waveCleared && this.databus.enemies.length === 0) {
      this.waveCleared = true;
      this.waveTimer = this.waveDelay;
      console.log('Wave cleared, starting delay for next wave');
    }
  }

  // 更新所有角色
  update() {
    // 更新玩家
    if (this.databus.player) {
      this.databus.player.update();
      
      // 检查玩家是否死亡
      if (this.databus.player.isDead && !this.databus.gameOver) {
        // 通知Main类处理游戏结束
        if (this.onGameOver) {
          this.onGameOver();
        }
      }
    }

    // 更新队友并输出调试信息
    this.databus.allies.forEach((ally, index) => {
      if (ally) {
        ally.update();
        console.log(`队友${index} - 位置: (${ally.x.toFixed(0)},${ally.y.toFixed(0)}) 状态: ${ally.visible ? '可见' : '隐藏'} 生命: ${ally.hp}/${ally.maxHp}`);
      }
    });

    // 更新敌人
    this.databus.enemies.forEach((enemy) => {
      enemy.update();
    });

    // 检查并移除死亡的敌人
    this.databus.enemies = this.databus.enemies.filter((enemy) => {
      if (enemy.isDying && enemy.blinkCount >= 10) {
        enemy.visible = false;
        this.databus.pool.recover('enemy', enemy);
        return false;
      }
      return true;
    });

    // 检查波次状态
    this.checkWaveStatus();

    // 如果当前波次结束，等待一段时间后开始新的波次
    if (this.waveCleared) {
      if (this.waveTimer > 0) {
        this.waveTimer--;
      } else {
        this.startNewWave();
      }
    }
  }

  // 渲染所有角色
  render(ctx) {
    // 渲染队友（在玩家下层）
    this.databus.allies.forEach((ally) => {
      if (ally.visible) {
        ally.render(ctx);
      }
    });

    // 渲染敌人
    this.databus.enemies.forEach((enemy) => {
      enemy.render(ctx);
    });

    // 渲染玩家（最后渲染，保证在最上层）
    if (this.databus.player) {
      this.databus.player.render(ctx);
    }

    // 如果在波次间隔，显示提示
    if (this.waveCleared && this.waveTimer > 0) {
      ctx.save();
      ctx.font = '30px Arial';
      ctx.fillStyle = '#FFFFFF';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(
        `Wave ${this.currentWave} Completed!`,
        SCREEN_WIDTH / 2,
        SCREEN_HEIGHT / 2 - 20
      );
      ctx.font = '20px Arial';
      ctx.fillText(
        `Next wave in ${Math.ceil(this.waveTimer / 60)}...`,
        SCREEN_WIDTH / 2,
        SCREEN_HEIGHT / 2 + 20
      );
      ctx.restore();
    }
  }

  // 重置管理器状态
  reset() {
    this.currentWave = 0;
    this.waveCleared = true;
    this.waveTimer = 0;
    
    // 清除所有敌人
    this.databus.enemies.forEach((enemy) => {
      enemy.visible = false;
      this.databus.pool.recover('enemy', enemy);
    });
    this.databus.enemies = [];
    
    // 重新初始化玩家
    this.initPlayer();
    
    console.log('CharacterManager reset');
  }
}